<template>
	<el-dialog title="分配权限" :visible.sync="dialogVisibleData" width="36%" @close="removed">
		<el-tree :data="list" :props="defaultProps" show-checkbox ref="tree" node-key="id" default-expand-all :default-checked-keys="keysDefault"></el-tree>

		<span slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible">取 消</el-button>
			<el-button type="primary" @click="dialogVisibled(list)">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script>
export default {
	name: 'Assignment',
	data() {
		return {
			dialogVisibleData: false,
			list: [],
			id: '',
			keysDefault: [],
			defaultProps: {
				children: 'children',
				label: 'authName',
			},
		}
	},
	methods: {
		dialogVisible() {
			this.dialogVisibleData = false
		},
		dialogVisibled() {
			let array = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
			let rids = array.join(',')
			this.$http
				.post(`/roles/${this.id}/rights`, {
					rids: rids,
				})
				.then(response => {
					let { meta } = response.data
					if (meta.status == 200) {
						this.$message({
							type: 'success',
							message: meta.msg,
						})
						this.$bus.$emit('Rolesreload')
					} else {

						this.$message.error('更新权限失败！')
					}
				})
				.catch(error => {
					console.log(error.message)
				})
			this.dialogVisibleData = false
		},
		getList() {
			this.$http
				.get('/rights/tree')
				.then(response => {
					let { data, meta } = response.data
					this.list = data
					if (meta.status != 200) {
						this.$message.error('获取权限列表成功失败!')
					}
				})
				.catch(error => {
					console.log(error.message)
				})
		},
		removed() {
			this.$nextTick(() => {
				this.$refs.tree.setCheckedKeys([])
			})
		},
	},
	created() {
		this.getList()
	},
	mounted() {

		this.$bus.$on('toggleBollean', () => {

			this.dialogVisibleData = true
		})
		this.$bus.$on('keysDefault', data => {
			this.keysDefault = data
		})
		this.$bus.$on('Roleauthorization', data => {
			this.id = data
		})
	},
}
</script>
